import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

const service: AxiosInstance = axios.create({
    baseURL: 'http://localhost:8085/admin',
    timeout: 10000
});

// 假设您将 Token 存储在 localStorage 中  
const getToken = () => {
    let result = JSON.parse(localStorage.getItem('loginUserInfo')); // 或者从 Cookie 中获取  
    return result != null ?result.token:'';
};
service.interceptors.request.use(

    (config: InternalAxiosRequestConfig) => {

        //全局拦截携带Token
        const token = getToken();
        //判断是否为首次请求
        if (token != null ) {
            config.headers['token'] = token; // 添加 Authorization 头  
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response;
        } else {
            return Promise.reject(new Error('Response status is not 200'));
        }
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject(error);
    }
);

export default service;